package com.kidback.bbloc259.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.kidback.bbloc259.R;


/**
 * 固定宽高比 FrameLayout
 * Created by meikai on 2019/8/1.
 */
public class ScaleFrameLayout extends FrameLayout {

    private float widthScale = 1;
    private float heightScale = 1;
    private int fixDirection = 0; //0:以宽为基准+宽高比来计算；1:以高为基准+宽高比来计算；

    public ScaleFrameLayout(Context context) {
        super(context);
        init(context, null, 0, 0);
    }

    public ScaleFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0, 0);
    }

    public ScaleFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {

        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ScaleFrameLayout, defStyleAttr, defStyleRes);
        widthScale = arr.getFloat(R.styleable.ScaleFrameLayout_width_scale_frame_layout, 1f);
        heightScale = arr.getFloat(R.styleable.ScaleFrameLayout_height_scale_frame_layout, 1f);
        fixDirection = arr.getInt(R.styleable.ScaleFrameLayout_fix_direction, 0);
        if (widthScale == 0) {
            widthScale = 1;
        }
        if (heightScale == 0) {
            heightScale = 1;
        }
        arr.recycle();
    }

    /**
     * 重新设置宽高比
     */
    public void setAspectRatio(float widthScale, float heightScale) {
        this.widthScale = widthScale;
        this.heightScale = heightScale;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (fixDirection == 0) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (widthSize * heightScale / widthScale);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int newHeightMode = MeasureSpec.makeMeasureSpec(height, heightMode);

            super.onMeasure(widthMeasureSpec, newHeightMode);
        } else {
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            int width = (int) (heightSize * widthScale / heightScale);
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int newWidthMode = MeasureSpec.makeMeasureSpec(width, widthMode);

            super.onMeasure(newWidthMode, heightMeasureSpec);
        }
    }

}
